package io.renren.modules.cardeal.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.Constant;
import io.renren.common.utils.JacksonUtils;
import io.renren.common.utils.PageData;
import io.renren.modules.cardeal.dao.CarDealDao;
import io.renren.modules.cardeal.dto.CarDealDTO;
import io.renren.modules.cardeal.entity.CarDealEntity;
import io.renren.modules.cardeal.service.CarDealService;
import io.renren.modules.cardeal.vo.CarDealVO;
import io.renren.modules.carinfo.entity.CarInfoEntity;
import io.renren.modules.carinfo.service.CarInfoService;
import io.renren.modules.carinsurance.entity.CarInsuranceEntity;
import io.renren.modules.carinsurance.service.CarInsuranceService;
import io.renren.modules.carinsurance.vo.CarInsuranceVO;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.user.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("carDealService")
public class CarDealServiceImpl extends ServiceImpl<CarDealDao, CarDealEntity> implements CarDealService {

    @Autowired
    private CarInsuranceService carInsuranceService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CarInfoService carInfoService;

    @Override
    public PageData<CarDealVO> queryCarDealPage(Map<String, Object> params) {
        log.info("车辆成交表(分页)");
        // 获取当前操作人的userId
        Long userId = SecurityUser.getUserId();
        // 获取信息
        String customerName = (String) params.get("customerName");
        Integer page = Integer.valueOf((String) params.get("page"));
        Integer limit = Integer.valueOf((String) params.get("limit"));
        Object startTime = params.get("startTime");
        Object endTime = params.get("endTime");
        QueryWrapper<CarDealEntity> wrapper = new QueryWrapper<CarDealEntity>();
        if (StringUtils.isNotBlank(customerName)) {
            wrapper.like("customer_name", customerName);
        }
        if (userId != Constant.SUPER_ADMIN) {
            wrapper.eq("creator", userId);
        }
        if (startTime != null && endTime != null) {
            wrapper.between("create_time", startTime, endTime);
        }
        wrapper.orderByDesc("create_time");
        // 创建分页对象
        IPage<CarDealEntity> iPage = new Page<CarDealEntity>(page, limit);
        this.baseMapper.selectPage(iPage, wrapper);
        // 分页集合
        List<CarDealEntity> records = iPage.getRecords();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<CarDealVO> customerInfoVOS = new ArrayList<CarDealVO>();
        for (CarDealEntity record : records) {
            CarDealVO carDealVO = JacksonUtils.obj2pojo(record, CarDealVO.class);
            // 查询保险
            String[] carInsuranceIds = record.getCarInsuranceId().split(",");
            List<CarInsuranceVO> carInsuranceVOList = new ArrayList<>();
            for (String carInsuranceId : carInsuranceIds) {
                CarInsuranceEntity insuranceEntity = carInsuranceService.getById(carInsuranceId);
                CarInsuranceVO carInsuranceVO = JacksonUtils.obj2pojo(insuranceEntity, CarInsuranceVO.class);
                carInsuranceVOList.add(carInsuranceVO);
            }
            carDealVO.setCarInsuranceVOList(carInsuranceVOList);
            carDealVO.setUpdateDate(simpleDateFormat.format(carDealVO.getUpdateTime()));
            carDealVO.setCreateDate(simpleDateFormat.format(carDealVO.getCreateTime()));
            carDealVO.setCreatorName(sysUserService.getById(carDealVO.getCreator()).getUsername());
            customerInfoVOS.add(carDealVO);
        }
        // 总数
        long total = iPage.getTotal();
        PageData<CarDealVO> pageData = new PageData<CarDealVO>(customerInfoVOS, total);
        return pageData;
    }

    @Override
    public void addCarDeal(CarDealDTO dto) {
        log.info("添加车辆成交");
        CarDealEntity carDealEntity = JacksonUtils.obj2pojo(dto, CarDealEntity.class);
        // 保险
        List<Long> carInsuranceIds = dto.getCarInsuranceIds();
        String carInsuranceId = carInsuranceIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        carDealEntity.setCarInsuranceId(carInsuranceId);
        this.baseMapper.insert(carDealEntity);
    }

    @Override
    public List<JSONObject> performance(Map<String, Object> params) {
        log.info("销售业绩统计");

        // 获取当前操作人的userId
        Long userId = SecurityUser.getUserId();
        Object startTime = params.get("startTime");
        Object endTime = params.get("endTime");
        QueryWrapper<CarDealEntity> wrapper = new QueryWrapper<CarDealEntity>();
        if (startTime != null && endTime != null) {
            wrapper.between("create_time", startTime, endTime);
        }
        if (userId != Constant.SUPER_ADMIN) {
            wrapper.eq("creator", userId);
            Integer count = this.baseMapper.selectCount(wrapper);
            String username = SecurityUser.getUser().getUsername();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username", username);
            jsonObject.put("count", count);
            List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
            jsonObjectList.add(jsonObject);
            return jsonObjectList;
        }
        List<CarDealEntity> carDealEntities = this.baseMapper.selectList(wrapper);
        // 按照销售进行分组
        Map<Long, List<CarDealEntity>> collect = carDealEntities.stream().collect(Collectors.groupingBy(e -> e.getCreator()));
        List<JSONObject> jsonObjectList = new ArrayList<JSONObject>();
        collect.keySet().forEach(e -> {
            JSONObject jsonObject = new JSONObject();
            SysUserEntity sysUserEntity = sysUserService.queryUserByUserId(e);
            jsonObject.put("username", sysUserEntity.getUsername());
            jsonObject.put("count", collect.get(e).size());
            jsonObjectList.add(jsonObject);
        });
        jsonObjectList.stream().sorted(Comparator.comparing(e -> e.getIntValue("count"))).collect(Collectors.toList());
        return jsonObjectList;
    }

    @Override
    public JSONObject caiwu(Map<String, Object> params) {
        Object startTime = params.get("startTime");
        Object endTime = params.get("endTime");
        QueryWrapper<CarDealEntity> wrapper = new QueryWrapper<CarDealEntity>();
        if (startTime != null && endTime != null) {
            wrapper.between("create_time", startTime, endTime);
        }
        List<CarDealEntity> carDealEntities = this.baseMapper.selectList(wrapper);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        carDealEntities.forEach(e -> {
            // 最终成交价
            BigDecimal finalPrices = e.getFinalPrices();
            String carNumber = e.getCarNumber();
            CarInfoEntity carInfoEntity = carInfoService.queryByNum(carNumber);
            // 指导价
            String guidePrice = carInfoEntity.getGuidePrice();
            BigDecimal bigDecimal = new BigDecimal(guidePrice);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("finalPrices", finalPrices);
            jsonObject.put("guidePrice", bigDecimal);
            jsonObjectList.add(jsonObject);
        });
        Integer finalPricess = jsonObjectList.stream().collect(Collectors.summingInt(e -> e.getIntValue("finalPrices")));
        Integer guidePrices = jsonObjectList.stream().collect(Collectors.summingInt(e -> e.getIntValue("guidePrice")));
        Integer lirun = finalPricess - guidePrices;
        JSONObject json = new JSONObject();
        json.put("finalPricess", finalPricess);
        json.put("guidePrices", guidePrices);
        json.put("lirun", lirun);
        return json;
    }

}
